package com.example.demo.job;

import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

/**
 * @program: SpringAOP
 * @ClassName QuartzConfig
 * @description:
 * @author: zsn
 * @create: 2024-11-26 14:43
 * @Version 1.0
 **/
@Configuration
public class QuartzConfig {

    // 创建SchedulerFactoryBean
    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() throws SchedulerException {
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        // 可以在这里设置Quartz的相关属性，如线程池大小、等待任务完成的超时时间等
        // factory.setWaitForJobsToCompleteOnShutdown(true);
        // factory.setThreadPoolSize(10);
//        Scheduler scheduler = factory.getScheduler();
//        scheduler.scheduleJob(myJobDetail(), myTrigger());
//        scheduler.start();
        return factory;
    }

    // 创建JobDetail
    @Bean
    public JobDetail myJobDetail() {
        return JobBuilder.newJob(MyQuartzJob.class)
                .withIdentity("myJob")
                .storeDurably()
                .build();
    }

    // 创建Trigger
    @Bean
    public Trigger myTrigger() {
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0/3 * * * * ?");
        return TriggerBuilder.newTrigger()
                .forJob(myJobDetail())
                .withIdentity("myTrigger")
                .withSchedule(scheduleBuilder)
                .build();
    }

}